<?php

namespace App\Console\Commands;

use App\Common\SwooleSocket;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class SwooleTest extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swoole-socket:start';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'swoole websocket';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
//        $a = [1,1,3,4,4,3,6];
//        $xors = 0;
//        for($i = 0;$i<7;$i++) {
//            $xors ^= $i;
//        }
//        for($i = 0;$i<count($a);$i++) {
//            $xors ^= $a[$i];
//        }
//        dd($xors);
//        SwooleSocket::getWebsocket();
        //创建websocket服务器对象，监听0.0.0.0:9502端口
        $ws = new \swoole_websocket_server("0.0.0.0", 8802);

//        $ws->on('workerStart', function ($ws, $workerId) {
//            $redis = new \Swoole\Coroutine\Redis();
//            $redis->connect('127.0.0.1', 6379);
//            if ($redis->subscribe(['channel-swoole'])) {
//                var_dump($redis->subscribe(['channel-swoole']));
//                $message = $redis->subscribe(['channel-swoole']);
//                foreach ($ws->connections as $fd) {
//                    $ws->push($fd, 'abcdefgggg');
//                }
//            }
//        });

        //监听WebSocket连接打开事件
        $ws->on('open', function ($ws, $request) {
            var_dump($request->fd, $request->get, $request->server);
            $ws->push($request->fd, "hello, welcome\n");
        });
        //监听WebSocket消息事件
        $ws->on('message', function ($ws, $frame) {
            echo "Message: {$frame->data}\n";
            $data = json_decode($frame->data,true);
            Redis::Hset($frame->fd,'username',$data['username']);

            $send_data = Redis::hget($frame->fd,'username');
            $ws->push($frame->fd, "server: {$send_data} hello!!!");
        });

        $ws->on('request', function ($request, $response) use ($ws){
            Log::info('log-swoole',['request'=>$request->get['message']]);
            // $server->connections 遍历所有websocket连接用户的fd，给所有用户推送
            var_dump($ws->connections);
            foreach ($ws->connections as $fd) {
                $ws->push($fd, $request->get['message']);
            }
        });

        //监听WebSocket连接关闭事件
        $ws->on('close', function ($ws, $fd) {
            echo "client-{$fd} is closed\n";
        });

        $ws->start();

    }
}
